# CCN::Daemon.pm
# (c) 2007, Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# Inspired by http://www.webreference.com/perl/tutorial/9/
# and the documentation for Tie::Syslog;
#

use strict; use warnings;

package CCN::Daemon;
use base qw(CCN::Syslogger);

sub initialize($)
{
    my ($self,$name) = @_;

    chdir('/')
        or $self->die ("Can't chdir to /: $!");
    # umask(0);
    open STDIN, '/dev/null'
        or $self->die ("Can't read /dev/null: $!");
    open STDOUT, '>', '/dev/null'
        or $self->die ("Can't open /dev/null: $!");

    my $forked = fork();
    $self->die ("Fork failed: $!") if not defined $forked;

    # Exit the parent process
    exit 0 if $forked != 0;

    $self->start_child($name);
}

sub start_child($)
{
    my ($self,$name) = @_;

    # Child process
    use POSIX;
    POSIX::setsid()
        or $self->die ("Can't start a new session: $!");

    # Syslogger initialize
    $self->SUPER::initialize($name);

    open STDERR, '>', '/dev/null'
        or $self->die ("Can't open /dev/null: $!");

}

1;